package com.dw.dwdzcommerce.tools.uiView.scrollListView;

import com.dw.dwdzcommerce.R;
import com.dw.dwdzcommerce.tools.commons.L;
import com.dw.dwdzcommerce.tools.uiView.xlistview.XListViewHeader;
import com.dw.dwdzcommerce.tools.uiView.xlistview.XListView.IXListViewListener;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.util.SparseArray;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.animation.DecelerateInterpolator;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.Scroller;
import android.widget.TextView;
import android.widget.FrameLayout.LayoutParams;

public class ScrollListView extends ScrollView {

	private static final int SCROLLBACK_HEADER = 0;
	private static final int SCROLL_DURATION = 400;
	private static final float OFFSET_RADIO = 1.8f;
	private static final String TAG = "TestMyListView";
	private XListViewHeader mHeaderView;
	private int mHeaderViewHeight;
	private SparseArray<View> mContentView;
	private LinearLayout mRootView;
	private boolean isOnTop = false;
	private Scroller mScroller;

	private RelativeLayout mHeaderViewContent;

	private TextView mHeaderTimeView;
	private boolean mPullRefreshing;
	private int mScrollBack;
	private float mLastY;
	private boolean mEnablePullRefresh = true;
	private IXListViewListener mListViewListener;
	private ListFooter mFooterView;

	public ScrollListView(Context context) {
		super(context);
		init(context);
	}

	public ScrollListView(Context context, AttributeSet attrs, int defStyleAttr) {
		super(context, attrs, defStyleAttr);
		init(context);
	}

	public ScrollListView(Context context, AttributeSet attrs) {
		super(context, attrs);
		init(context);
	}

	private void init(Context context) {
		mScroller = new Scroller(context, new DecelerateInterpolator());

		mHeaderView = new XListViewHeader(context);
		mHeaderViewContent = (RelativeLayout) mHeaderView.findViewById(R.id.xlistview_header_content);
		mHeaderTimeView = (TextView) mHeaderView.findViewById(R.id.xlistview_header_time);

		// 初始化 header 高度
		mHeaderView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {// 当layout的状态或可见性发生改变时回调
			@Override
			public void onGlobalLayout() {
				mHeaderViewHeight = mHeaderViewContent.getHeight();
				getViewTreeObserver().removeGlobalOnLayoutListener(this);
			}
		});

		setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
		mRootView = new LinearLayout(context);
		mRootView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
		mRootView.setOrientation(LinearLayout.VERTICAL);
		mRootView.setPadding(1, 1, 1, 1);

		mRootView.addView(mHeaderView);
		addView(mRootView);
	}

	public void setAdapter(ListAdapter adapter) {
		int childCount = adapter.getCount();
		mContentView = new SparseArray<View>(childCount);
		for (int i = 0; i < childCount; i++) {
			View convertView = null;
			convertView = adapter.getView(i, convertView, null);
			mContentView.append(i, convertView);
			mRootView.addView(convertView);
		}
		addFooter();
	}

	public void setOnFooterClickListener(OnClickListener listener) {
		mFooterView.setOnClickListener(listener);
	}

	private void addFooter() {
		mFooterView = new ListFooter(getContext());
		mFooterView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
		mRootView.addView(mFooterView);
	}

	public void setPullRefreshEnable(boolean enable) {
		mEnablePullRefresh = enable;
		if (!mEnablePullRefresh) { // disable, hide the content
			mHeaderViewContent.setVisibility(View.INVISIBLE);
		} else {
			mHeaderViewContent.setVisibility(View.VISIBLE);
		}
	}

	public void stopRefresh() {
		if (mPullRefreshing == true) {
			mPullRefreshing = false;
			resetHeaderHeight();
		}
	}

	private void resetHeaderHeight() {
		int height = mHeaderView.getVisiableHeight();
		if (height == 0) // not visible.
			return;
		// refreshing and header isn't shown fully. do nothing.
		if (mPullRefreshing && height <= mHeaderViewHeight) {
			return;
		}
		int finalHeight = 0; // default: scroll back to dismiss header.
		// is refreshing, just scroll back to show all the header.
		if (mPullRefreshing && height > mHeaderViewHeight) {
			finalHeight = mHeaderViewHeight;
		}
		mScrollBack = SCROLLBACK_HEADER;
		mScroller.startScroll(0, height, 0, finalHeight - height, SCROLL_DURATION);
		// trigger computeScroll
		invalidate();

	}

	@Override
	public boolean onInterceptTouchEvent(MotionEvent ev) {
		if (ev.getAction() == MotionEvent.ACTION_DOWN) {
			mLastY = ev.getRawY();
			L.i(TAG, "mLastY=" + mLastY);
		}
		return super.onInterceptTouchEvent(ev);
	}

	@Override
	public boolean onTouchEvent(MotionEvent ev) {
		if (mLastY == -1) {
			mLastY = ev.getRawY();
		}

		switch (ev.getAction()) {
		case MotionEvent.ACTION_DOWN:
			//此处由于被child消费，所以不能在这里获取点击位置
			break;
		case MotionEvent.ACTION_MOVE:
			final float deltaY = ev.getRawY() - mLastY;
			Log.i(TAG, "deltaY=" + deltaY);
			mLastY = ev.getRawY();
			if (isOntheTop() && (mHeaderView.getVisiableHeight() > 0 || deltaY > 0)) {
				// the first item is showing, header has shown or pull down.
				Log.i(TAG, "updateHeaderHeight");
				updateHeaderHeight(deltaY / OFFSET_RADIO);
			}
			break;
		default:
			mLastY = -1; // reset
			if (isOntheTop()) {
				// invoke refresh
				if (mEnablePullRefresh && mHeaderView.getVisiableHeight() > mHeaderViewHeight) {
					mPullRefreshing = true;
					mHeaderView.setState(XListViewHeader.STATE_REFRESHING);
					if (mListViewListener != null) {
						mListViewListener.onRefresh();
					}
				}
				resetHeaderHeight();
			}
			break;
		}
		return super.onTouchEvent(ev);
	}

	private void updateHeaderHeight(float delta) {
		mHeaderView.setVisiableHeight((int) delta + mHeaderView.getVisiableHeight());
		if (mEnablePullRefresh && !mPullRefreshing) { // 未处于刷新状态，更新箭头
			if (mHeaderView.getVisiableHeight() > mHeaderViewHeight) {
				mHeaderView.setState(XListViewHeader.STATE_READY);
			} else {
				mHeaderView.setState(XListViewHeader.STATE_NORMAL);
			}
		}
		scrollTop(); // scroll to top each time
	}

	private void scrollTop() {
		scrollTo(0, 0);
	}

	@Override
	public void computeScroll() {
		if (mScroller.computeScrollOffset()) {
			if (mScrollBack == SCROLLBACK_HEADER) {
				mHeaderView.setVisiableHeight(mScroller.getCurrY());
			}
			postInvalidate();
		}
		super.computeScroll();
	}

	// @Override
	// protected boolean overScrollBy(int deltaX, int deltaY, int scrollX, int
	// scrollY, int scrollRangeX, int scrollRangeY,
	// int maxOverScrollX, int maxOverScrollY, boolean isTouchEvent) {
	//
	// int newScrollY = scrollY + deltaY;
	//
	// final int bottom = maxOverScrollY + scrollRangeY;
	//
	// final int top = -maxOverScrollY;
	//
	// if (newScrollY > bottom) {
	//
	// System.out.println("滑动到底端");
	//
	// }
	//
	// else if (newScrollY < top) {
	//
	// isOnTop = true;
	//
	// } else {
	// isOnTop = false;
	// }
	//
	// return super.overScrollBy(deltaX, deltaY, scrollX, scrollY, scrollRangeX,
	// scrollRangeY, maxOverScrollX,
	// maxOverScrollY, isTouchEvent);
	// }

	private boolean isOntheTop() {
		int scrollY = getScrollY();
		Log.i(TAG, "scrollY=" + scrollY);
		int visiableHeight = mHeaderView.getVisiableHeight();
		Log.i(TAG, "visiableHeight=" + visiableHeight);
		return scrollY - visiableHeight <= 0;

	}

	public void setmListViewListener(IXListViewListener mListViewListener) {
		this.mListViewListener = mListViewListener;
	}
}
